const { app, BrowserWindow, screen, ipcMain, dialog, nativeImage } = require('electron')
const { showTooltip, hideTooltip } = require('./tooltip');
const { showBindTo, hideBindTo, getBindToCurrentUid, getBindToCurrentFansUid } = require('./bindTo');
const { showGinftReBindTo, hideGiftRebindTo, getCurrentGift_id, getCurrentRev_user_id } = require('./giftRebindTo');
const fs = require('fs').promises;
const path = require('node:path')
const db = require('./db/database.js')
const { ALL } = require('node:dns');
const Main = require('electron/main');
const { type } = require('os');

const user_code = 'peng chao'

let mainWin
let mobileFrame
let mobileFrameMoni = false
let hookWin
let selectAddComponentsWin
let addUserAlert
let selectGifAlert
let redbookRoomStatus = 0  // 0未连接 1连接中 2待开播 3开播中
let redbookRoomStatusRefreshTime = 0
let redbookRoomStatusMsgTime = 0
let redbookRoomStatusRefreshTimer = null
let mobileEdit = false
let editUserInfo

let wins = []

// 所有场景
let allMobleScene
let currentSceneIndex = -1
let currentScene

// 主播列表
let userList
let editUserIndex = -1

// npm install electron-debug@3.1.0  # 3.x 版本支持 CommonJS
// "scripts": {
//     "start": "electron .",
// 	"debug": "electron --inspect=9229 .",
// npm run debug chrome://inspect
// 是否自动绑定
require('electron-debug')({
  showDevTools: false,  // 不自动打开渲染进程调试工具
  devToolsMode: 'undocked',  // 如果开启，则分离窗口
  isEnabled: true  // 启用主进程调试
});

// 定时器 -- start
let nextSecond = Date.now() + (1000 - (Date.now() % 1000));
function alignedTick(callback) {
	const now = Date.now();
	const delay = nextSecond - now;
	if (delay > 0) {
		setTimeout(() => {
			callback();
			nextSecond += 1000; // 更新下一个整秒时间
			alignedTick(callback); // 递归调用
		}, delay);
	} else {
		// 如果已经错过，立即执行并调整
		callback();
		nextSecond = now + 1000 - (now % 1000);
		alignedTick(callback);
	}
}

// 使用
alignedTick(() => {
	if (currentSceneIndex != -1 && allMobleScene.length > currentSceneIndex) {
		const scene = allMobleScene[currentSceneIndex]
		let updated = false
		for (let cpt of scene.allComponents) {
			if (cpt.countdown_status && cpt.countdown_status == 1) {
				let current_countdown = cpt.current_countdown - 1
				if (current_countdown <= 0) {
					current_countdown = 0
					cpt.countdown_status = 0
				}
				cpt.current_countdown = current_countdown
				db.updateCptTable(cpt)
				updated = true
			}
		}
		// 有更新
		if (updated) {
			for (let win of wins) {
				if (win != null && !win.isDestroyed()) {
					//  在用
					win.webContents.send('notice-scene-changed', scene, currentSceneIndex, -1, 'all')
				}
			}
		}
	}
})
// 定时器 -- end

function createMainWin() {

	const primaryDisplay = screen.getPrimaryDisplay()
	const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize
	mainWin = new BrowserWindow({
		width: 1424,
		height: 500,
		minWidth: 1424,
		x: screenWidth - 1424,
		y: screenHeight - 540,
		// frame: false,
		// transparent: true,
		// autoHideMenuBar: true,
		backgroundColor: "#0e0e11",
		webPreferences: {
			preload: path.join(__dirname, 'preload.js')
		}
	})
	wins.push(mainWin)
	mainWin.setBackgroundThrottling(false)
	mainWin.loadURL('http://localhost:8080/#/')
	// 当焦点窗口关闭时重新启用其他窗口
	mainWin.on('closed', () => {
	  BrowserWindow.getAllWindows().forEach(win => {
	    win.close()
	  })
	})
}

function createAddUserAlert(userInfo) {
	
	const topWindow = BrowserWindow.getFocusedWindow()
	if (addUserAlert == null || addUserAlert.isDestroyed()) {
		addUserAlert = new BrowserWindow({
			width: 300,
			height: 500,
			// minWidth: 300,
			// maxWidth: 300,
			// minHeight: 500,
			// maxHeight: 500,
			backgroundColor: "#0e0e11",
			webPreferences: {
				preload: path.join(__dirname, 'preload.js')
			}
		})
		wins.push(addUserAlert)
	}
	addUserAlert.loadURL('http://localhost:8080/#/pages/add-user-alert/add-user-alert')
	
	// 禁用其他窗口
	BrowserWindow.getAllWindows().forEach(win => {
	  if (win !== addUserAlert) {
	    win.setEnabled(false)  // 禁用窗口交互
	  }
	})
	
	// 当焦点窗口关闭时重新启用其他窗口
	addUserAlert.on('closed', () => {
	  BrowserWindow.getAllWindows().forEach(win => {
	    win.setEnabled(true)
		win.moveTop()
	  })
	  topWindow.moveTop()
	})
}

function createSelectGifAlert(userInfo) {
	
	const topWindow = BrowserWindow.getFocusedWindow()
	
	if (selectGifAlert == null || selectGifAlert.isDestroyed()) {
		selectGifAlert = new BrowserWindow({
			modal: true,
			width: 800,
			height: 500,
			// minWidth: 300,
			// maxWidth: 300,
			// minHeight: 500,
			// maxHeight: 500,
			backgroundColor: "#0e0e11",
			webPreferences: {
				preload: path.join(__dirname, 'preload.js')
			}
		})
		wins.push(selectGifAlert)
	}

	// 禁用其他窗口
	BrowserWindow.getAllWindows().forEach(win => {
	  if (win !== selectGifAlert) {
	    win.setEnabled(false)  // 禁用窗口交互
	  }
	})
	
	// 当焦点窗口关闭时重新启用其他窗口
	selectGifAlert.on('closed', () => {
	  BrowserWindow.getAllWindows().forEach(win => {
		  
		  if (addUserAlert != null && !addUserAlert.isDestroyed()) {
			  if (win !== addUserAlert) {
					win.setEnabled(false)  // 禁用窗口交互
			  } else {
					win.setEnabled(true)
			  }
		  } else {
			  win.setEnabled(true)
		  }
		win.moveTop()
	  })
	  topWindow.moveTop()
	})
}

function createMobileFrame() {
	const primaryDisplay = screen.getPrimaryDisplay()
	const { height: screenHeight } = primaryDisplay.workAreaSize
	let h = parseInt(screenHeight * 0.9)
	// let w = parseInt(h * 1179 / 2556)
	let w = parseInt(h * 9 / 16)
	// const primaryDisplay = screen.getPrimaryDisplay()
	// const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize
	// let mh = parseInt(screenHeight * 0.9)
	// let mw = parseInt(mh * 1179 / 2556)
	
	mobileFrame = new BrowserWindow({
		title: '投放中',
		resizable: false,
		width: w,
		height: h,
		x: 40,
		y: screenHeight - h - 48,
		frame: false,
		transparent: true,
		webPreferences: {
			preload: path.join(__dirname, 'preload.js')
		}
	})
	// 当焦点窗口关闭时重新启用其他窗口
	mobileFrame.on('closed', () => {
		if (!mainWin.isDestroyed()) {
			createMobileFrame()
		}
	})
	// mobileFrame.webContents.setAppUserModelId('com.pc.mobile.tbb')
	// 防止网页动态修改标题
	mobileFrame.on('page-title-updated', (e) => {
		e.preventDefault() // 阻止标题被网页修改
	})
	wins.push(mobileFrame)
	mobileFrame.setBackgroundThrottling(false)
	mobileFrame.loadURL('http://localhost:8080/#/pages/mobile-frame/mobile-frame')

	if (mainWin != null && !mainWin.isDestroyed()) {
		mainWin.webContents.send('on-mobile-frame-set-min-or-max', false)
	}
}

function loadMobileFrame() {
	// 从数据库中读取场景
	if (allMobleScene.length > 0) {
		// currentScene = allMobleScene[0]
		currentSceneIndex = 0
		mobileEdit = true
		createMobileFrame()
	}
}

function setRedbookRoomStatus(status) {
	if (redbookRoomStatus != status) {
		redbookRoomStatus = status
		if (mainWin != null && !mainWin.isDestroyed()) {
			mainWin.webContents.send('on-redbook-room-status-changed', redbookRoomStatus);
		}
	}
}

function sendMsgToWin(win, msg) {
	if (win != null && !win.isDestroyed()) {
		win.webContents.send('received-msg', msg);
	}
}

/**
 * 数据解密
 * @param {Object} encoded 加密数据
 */
function Atob(encoded) {
	try {
		
		// 使用 atob 解码 base64 字符串
		let decoded = atob(encoded);
		
		const bytes = new Uint8Array(decoded.length);
		    for (let i = 0; i < decoded.length; i++) {
		        bytes[i] = decoded.charCodeAt(i);
		    }
		    decoded = new TextDecoder('utf-8').decode(bytes);
		    // console.log("方法2:", decoded);
		return JSON.parse(decoded);
	} catch (err) {
		// 返回错误信息
		console.error('Base64 解码失败:', err);
		return null;
	}
}

function insertConsole_story(msg, type) {
	let info = {
		user_code: user_code,
		desc: msg,
		create_time: Math.floor(Date.now() / 1000),
		type: type
	}
	info.id = db.insertConsole_story(info)
	if (mainWin != null && !mainWin.isDestroyed()) {
		mainWin.webContents.send('on-consoloe-story-add', info);
	}
}

function openRedbookRoom() {
	if (hookWin == null || hookWin.isDestroyed()) {
		hookWin = new BrowserWindow({ 
			width: 1200,
			height: 700,
			// autoHideMenuBar: false,
			webPreferences: { nodeIntegration: false } ,
		})
		hookWin.on('closed', () => {
			setRedbookRoomStatus(0)
			insertConsole_story('连接已断开', 'system')
		})
		hookWin.webContents.debugger.attach('1.3')
		hookWin.webContents.debugger.sendCommand('Network.enable')
		hookWin.webContents.debugger.on('message', (event, method, params) => {
			if (method === 'Network.webSocketFrameReceived') {
				// console.log(params.response)
				redbookRoomStatusMsgTime = Math.floor(Date.now() / 1000)
				if (redbookRoomStatus == 1 || redbookRoomStatus == 0) {
					setRedbookRoomStatus(2)
					insertConsole_story('通信连接成功,尝试连接直播间...', 'system')
				}
				// console.log(params.response)
				const payload = JSON.parse(params.response.payloadData)
				try {
					// 可能出错的代码
					// console.log(Atob(payload.b.d.b[0].d))
					// sendMsgToWin(mainWin, payload.b.d.b[0].d)
					analysisMsg(payload.b.d.b[0].d)
					// setRedbookRoomStatus(3)
				} catch (error) {
					// setRedbookRoomStatus(2)
					// if (redbookRoomStatus == 1) {
					// 	insertConsole_story('连接成功...')
					// } else {
					// 	insertConsole_story('待开播信息...')
					// }
				}
				// 可进行 Base64 解码和结构解析
			}
		})
	}
	db.delConsoleStory()
	hookWin.loadURL('https://redlive.xiaohongshu.com/live_center_control');
	redbookRoomStatusMsgTime = Math.floor(Date.now() / 1000)
	setRedbookRoomStatus(1)
	insertConsole_story('与小红书建立连接...', 'system')
	redbookRoomStatusRefreshTimer = setInterval(() => {
		// 0未连接 1连接中 2待开播 3开播中
		const nTime = Math.floor(Date.now() / 1000)
		// 非断开状态
		if (redbookRoomStatus > 0) {
			// 断开了连接
			if (nTime - redbookRoomStatusMsgTime > 60) {
				setRedbookRoomStatus(0)
				insertConsole_story('连接已断开', 'system')
			}
		}
		if (redbookRoomStatus == 3) {
			// 未断开连接，但是已经没有开播了
			if (nTime - redbookRoomStatusRefreshTime > 10) {
				setRedbookRoomStatus(2)
				insertConsole_story('直播停止', 'system')
			}
		}
	}, 1000)
}

function noticeEditChanged(edit) {
	mobileEdit = edit
	if (mobileFrame != null && !mobileFrame.isDestroyed()) {
		mobileFrame.webContents.send('mobile-scene-is-edit-changed', mobileEdit);
	}
	if (mainWin != null && !mainWin.isDestroyed()) {
		mainWin.webContents.send('mobile-scene-is-edit-changed', mobileEdit);
	}
	// 如果切换到编辑状态，自动手机模拟器会为
	if (mobileEdit && mobileFrameIsMin()) {
		if (mobileFrame != null && !mobileFrame.isDestroyed()) {
			const primaryDisplay = screen.getPrimaryDisplay()
			const { height: screenHeight } = primaryDisplay.workAreaSize
			let h = parseInt(screenHeight * 0.9)
			mobileFrame.setPosition(40, screenHeight - h - 48)
			if (mainWin != null && !mainWin.isDestroyed()) {
				mainWin.webContents.send('on-mobile-frame-set-min-or-max', false)
			}
		}
	}
}


function createComponentBaseInfo(cmpt_name, style) {
	const temp_id = db.randomNumStr12()
	if (cmpt_name == 'blood_bar') {
		const title = {
			'blood_bar': 'PK血条',
			'blood_sin': '擂台血条'
		}
		return {
			table_name: 'blood_bar',
			temp_id: temp_id,
			id: null,
			scene_id: allMobleScene[currentSceneIndex].id,
			title: title[style],
			x: 0,
			y: 50,
			scale: 0.7,
			opacity: 1,
			countdown: 120,
			current_countdown: 120,
			countdown_status: 0,
			share_countdown: 0,
			use_user_icon: 1,
			auto_bind: 1,
			style: style,
			rounds: 1,
			show: 1
		}
	}
	if (cmpt_name == 'gifts') {
		return {
			table_name: 'gifts',
			temp_id: temp_id,
			id: null,
			scene_id: allMobleScene[currentSceneIndex].id,
			title: '礼物',
			x: 0,
			y: 50,
			scale: 0.7,
			space: 50,
			opacity: 1,
			auto_bind: 1,
			style: style,
			show: 1
		}
	}
	if (cmpt_name == 'rank') {
		const title = {
			'rank': '普通排行榜',
		}
		return {
			table_name: 'rank',
			temp_id: temp_id,
			id: null,
			scene_id: allMobleScene[currentSceneIndex].id,
			title: title[style],
			x: 0,
			y: 50,
			scale: 0.7,
			opacity: 1,
			countdown: 120,
			current_countdown: 120,
			countdown_status: 0,
			share_countdown: 0,
			max_show_num: 5,
			style: style,
			show: 1
		}
	}
}

function sendInfoToHtml(noti_name, opt, needEdit) {
	if (needEdit && !mobileEdit) {
		return
	}
	if (mobileFrame != null && !mobileFrame.isDestroyed()) {
		mobileFrame.webContents.send(noti_name, opt)
	}
	if (mainWin != null && !mainWin.isDestroyed()) {
		mainWin.webContents.send(noti_name, opt)
	}
}

function mobileFrameIsMin() {
	if (mobileFrame == null || mobileFrame.isDestroyed()) {
		return false
	}
	const primaryDisplay = screen.getPrimaryDisplay()
	const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize
	return mobileFrame.getPosition()[0] == screenWidth && mobileFrame.getPosition()[1] == screenHeight
}



function analysisMsg(msg) {
	// console.log(msg)
	const msgData = Atob(msg)
	const customData = JSON.parse(msgData.customData)
	// 加入直播间
	// console.log(customData.type)
	// 加入直播间
	if (customData.type == 'refresh') {
		
		const nTime = Math.floor(Date.now() / 1000)
		redbookRoomStatusRefreshTime = nTime
		// 0未连接 1连接中 2待开播 3开播中
		if (redbookRoomStatus == 2) {
			setRedbookRoomStatus(3)
			insertConsole_story('直播间连接成功...', customData.type)
			
			// 排行榜发生变化
			if (mainWin != null && !mainWin.isDestroyed()) {
				mainWin.webContents.send('on-fans-sort-changed')
				mainWin.webContents.send('on-now-fans-sort-changed')
			}
		}
		db.updateSystem_setting('room_id', msgData?.roomId)
		
		// console.log(customData)
		// console.log('房间roomId:' + msgData?.roomId)
		// console.log('消息ID:' + msgData?.msgId)
		// console.log('房间观众：【')
		// for (let s of customData?.room_data?.viewers) {
		// 	console.log('            user_id:' + s.user_id)
		// 	console.log('            nickname:' + s.nickname)
		// 	console.log('            avatar:' + s.avatar)
		// 	console.log(',')
		// }
		// console.log('            】')
	}

	if (customData.type == 'audience_join_v2') {
		console.log(customData)
		console.log('用户头像' + customData?.profile?.avatar)
		console.log('用户昵称' + customData?.profile?.nickname)
		console.log('用户user_id' + customData?.profile?.user_id)
		console.log('房间roomId:' + msgData?.roomId)
		console.log('消息ID:' + msgData?.msgId)
		db.insertFans({
			user_code: user_code,
			user_id: customData?.profile?.user_id,
			nick_name: customData?.profile?.nickname,
			avatar: customData?.profile?.avatar,
			coins: 0,
			bind_uid: 0
		})
		insertConsole_story(customData?.profile?.nickname + '加入直播间', customData.type)
	}
	
	// 评论
	if (customData.type == 'text') {
		console.log(customData)
		console.log('用户头像' + customData?.profile?.avatar)
		console.log('用户昵称' + customData?.profile?.nickname)
		console.log('用户user_id' + customData?.profile?.user_id)
		console.log(customData.desc)
		console.log('房间roomId:' + msgData?.roomId)
		console.log('消息ID:' + msgData?.msgId)
		insertConsole_story(customData?.profile?.nickname + '说：' + customData.desc, customData.type)
	}
	// 点赞
	if (customData.type == 'praise') {
		if (customData?.profile?.user_id) {
			const fans = db.selectFans(customData?.profile?.user_id, user_code)
			if (fans) {
				insertConsole_story(fans.nick_name + '点赞' + customData.praise_info.count + '次', customData.type)
			} else {
				insertConsole_story(customData?.profile?.user_id + '点赞' + customData.praise_info.count + '次', customData.type)
			}
		}
		
		// console.log(customData?.profile)
		// console.log('用户头像' + customData?.profile?.avatar)
		// console.log('用户昵称' + customData?.profile?.nickname)
		// console.log('用户user_id' + customData?.profile?.user_id)
		// console.log('点赞次数:' + customData.praise_info.count)
		// console.log('房间roomId:' + msgData?.roomId)
		// console.log('消息ID:' + msgData?.msgId)
		// insertConsole_story(customData?.profile?.nickname + '点赞' + customData.praise_info.count + '次')
	}
	
	// 每次送礼均会收到，包括连击
	if (customData.type == 'gift_dock_and_effect') {
		// console.log(customData)
		// console.log('用户头像' + customData?.send_user_info?.avatar)
		// console.log('用户昵称' + customData?.send_user_info?.nick_name)
		// console.log('用户user_id' + customData?.send_user_info?.id)
		// console.log('礼物票:' + customData?.base_gift_info?.coins)
		// console.log('礼物id:' + customData?.base_gift_info?.id)
		// console.log('礼物名字:' + customData?.base_gift_info?.name)
		// console.log('礼物图标:' + customData?.base_gift_info?.icon)
		// console.log('房间roomId:' + msgData?.roomId)
		// console.log('消息ID:' + msgData?.msgId)
		
		// 更新粉丝的总送礼数
		db.updateFansCoins({
			user_code: user_code,
			user_id: customData?.send_user_info?.id,
			coins: customData?.base_gift_info?.coins
		})

		const nTime = Math.floor(Date.now() / 1000)
		
		// 判断是否自动绑定
		const autoBind = db.selectSystem_setting('auto_bind').value == 1

		// 下面的操作只是将 设定 该礼物为专属礼物的主播绑定给该粉丝
		// 获取拥有该专属礼物的主播 并且 他是show的状态
		const theGiftUserInfo = db.getUserInfoWithGiftId(user_code, customData?.base_gift_info?.id)

		// 要自动绑定
		if (autoBind) {
	
			// 获取到拥有该专属礼物的主播
			if (theGiftUserInfo) {
				// 判断这个主播是否在当前场景控件中
				let inIt = false
				for (let cpt of allMobleScene[currentSceneIndex].allComponents) {
					const tName = cpt.table_name + '_user_temp'
					for (let user of userList) {
						// 礼物表临时数据
						const user_cpt_temp = db.selectTableTemp(tName, user.id, cpt.id, user_code)
						if (user_cpt_temp && user_cpt_temp.u_id == theGiftUserInfo.id && user_cpt_temp.position != 0) {
							inIt = true
							break
						}
					}
				}
				// bind_user_id = theGiftUserInfo.id
				// 将这个专属礼物主播绑定给该粉丝
				if (inIt) {
					db.updateFansBind({
						bind_uid: theGiftUserInfo.id,
						user_id: customData?.send_user_info?.id,
						user_code: user_code
					})
				}
				// 给当前场景所有组件涉及到的主播加分

			}
		}

		// 礼物接受者(主播)
		let rev_user_id = 0
		// 查看这个粉丝数据，拿到他绑定的主播
		const localFansInfo = db.selectFans(customData?.send_user_info?.id, user_code)

		if (localFansInfo) {
		
			// 判断这个主播是否在当前场景控件中
			let inIt = false
			for (let cpt of allMobleScene[currentSceneIndex].allComponents) {
				const tName = cpt.table_name + '_user_temp'
				for (let user of userList) {
					// 礼物表临时数据
					const user_cpt_temp = db.selectTableTemp(tName, user.id, cpt.id, user_code)
					if (user_cpt_temp && user_cpt_temp.u_id == localFansInfo.bind_uid && user_cpt_temp.position != 0) {
						inIt = true
						break
					}
				}
			}
	
			if (inIt) {
				rev_user_id = localFansInfo.bind_uid
			}
		}

		// 虽然可能因为有绑定关系已经拿到了接收礼物的主播、但有可能因为组件的原因，不受绑定关系控制，如PK血条、计时器表演拉票
		// 查询当前场景下的组件
		let mappToTempTableInfos = []
		if (currentSceneIndex != -1) {
			for (let cpt of allMobleScene[currentSceneIndex].allComponents) {
				const tName = cpt.table_name + '_user_temp'
		
				for (let user of userList) {
					// 礼物表临时数据
					const user_cpt_temp = db.selectTableTemp(tName, user.id, cpt.id, user_code)
					if (user_cpt_temp && user_cpt_temp != null && type(user_cpt_temp) != 'undefined') {

						user_cpt_temp.table_name = tName
						// 如果这个粉丝绑定了主播 判断这个人是否是当前粉丝的绑定者
				
						if (rev_user_id != 0) {
						
							// 这个人是粉丝绑定的主播
							if (rev_user_id == user_cpt_temp.u_id) {
				
								// 如果是血条，需要判定该角色施法在pk位置上
								if (user_cpt_temp.position != 0) {
									user_cpt_temp.coins += customData?.base_gift_info?.coins
									db.updateTableTemp(user_cpt_temp)
									// 用于一会插入历史数据进入的组件对应表中
									mappToTempTableInfos.push(user_cpt_temp)
								}
							} else {
						
								// 这个人不是被绑定的主播
								// 查看这个主播的专属礼物是否是该礼物、在非自动绑定情况下会出现这种情况，但在自动绑定情况下是不会进入这段代码块的
								if (theGiftUserInfo && theGiftUserInfo.id == user_cpt_temp.u_id) {
					
									// 如果是血条，需要判定该角色施法在pk位置上
									if (user_cpt_temp.position != 0) {
										user_cpt_temp.coins += customData?.base_gift_info?.coins
										db.updateTableTemp(user_cpt_temp)
										rev_user_id = user_cpt_temp.u_id
										// 用于一会插入历史数据进入的组件对应表中
										mappToTempTableInfos.push(user_cpt_temp)
									}
								}
							}
						} else {
				
							// 查看专属礼物主播是不是这个主播
							if (theGiftUserInfo && theGiftUserInfo.id == user_cpt_temp.u_id) {
			
								// 如果是血条PK，需要判断是否在pk席位
								if (user_cpt_temp.position != 0) {
									user_cpt_temp.coins += customData?.base_gift_info?.coins
									db.updateTableTemp(user_cpt_temp)
									// 用于一会插入历史数据进入的组件对应表中
									mappToTempTableInfos.push(user_cpt_temp)
								}
							}
						}
					}
				}
			}
		}
		// 将礼物数据插入 gifts_story 礼物历史记录表
		const insertInfo = {
			table_name: 'gifts_story',
			rev_user_id: rev_user_id,
			user_id: customData?.send_user_info?.id,
			gift_source_id: customData?.base_gift_info?.id + "",
			gift_icon: "/static/gifts_imgs/" + customData?.base_gift_info?.id + ".png",
			gift_name: customData?.base_gift_info?.name,
			gift_coins: customData?.base_gift_info?.coins,
			create_time: nTime,
			room_id: msgData?.roomId,
			user_code: user_code
		}
		const gSId = db.insertTableTemp(insertInfo, true)
		for (let user_cpt_tempInfo of mappToTempTableInfos) {
			db.insertTableTemp({
				table_name: 'user_temp_mapping',
				u_id: user_cpt_tempInfo.u_id,
				cpt_id: user_cpt_tempInfo.cpt_id,
				cpt_t_name: user_cpt_tempInfo.table_name,
				gift_id: gSId,
				coins: insertInfo.gift_coins,
				user_code: user_code
			})
		}

		// 有接受者
		if (rev_user_id != 0) {
			for (let user of userList) {
				if (user.id == rev_user_id) {
					const room_id = db.selectSystem_setting('room_id').value
					const total_gift_coins = db.totalBind_user_idGiftCoins(user.id)
					user.total_gift_coins = total_gift_coins
					if (room_id == 0 || room_id == null) {
						user.now_gift_coins = 0
					} else {
						user.now_gift_coins = db.nowBind_user_idGiftCoins(user.id, room_id)
					}
					break
				}
			}
		}

		
		// 通知关系数据有变化
		for (let win of wins) {
			if (win != null && !win.isDestroyed()) {
				//  在用
				win.webContents.send('notice-user-cpt-temp-changed', 'all')
				win.webContents.send('notice-user-list-changed', userList, 'all')
			}
		}
		
		// 排行榜发生变化
		if (mainWin != null && !mainWin.isDestroyed()) {
			mainWin.webContents.send('on-fans-sort-changed')
			mainWin.webContents.send('on-now-fans-sort-changed')
		}
		insertConsole_story(customData?.send_user_info?.nick_name + '送礼' + customData?.base_gift_info?.name + ' 价值' + customData?.base_gift_info?.coins + '票', customData.type)
		
		
	}
	
	// 每次送礼彻底完毕后收到，连击只收到最后一次
	if (customData.type == 'gift_comment') {
		// console.log(customData)
	}
}

app.whenReady().then(async () => {
	
	ipcMain.on('tooltip:show', (event, { x, y, text }) => showTooltip(x, y, text));
	ipcMain.on('tooltip:hide', hideTooltip);
	
	db.initDB() // 初始化数据库结构
	// 清空控制面板日志信息
	db.delConsoleStory()
	db.insertSystem_setting([
		{
			setting: 'auto_bind',
			value: '1'
		},
		{
			setting: 'user_code',
			value: user_code
		},
		{
			setting: 'room_id',
			value: '0'
		}
	])
	// 获取所有场景
	allMobleScene = db.getMobleScene(user_code)
	// 获取所有用户列表
	userList = db.getUserList(user_code)

	createMainWin()
	loadMobileFrame()

	// 打开小红书直播间
	ipcMain.on('link-redbook-room', (event) => {
		openRedbookRoom()
	})

	// 返回小红书直播间链接状态
	ipcMain.handle('redbook-room-status', () => {
		if (hookWin == null || hookWin.isDestroyed()) return 0
		return redbookRoomStatus
	})
	
	// 保存手机显示内容
	ipcMain.on('save-mobile-data', (event) => {
		openRedbookRoom()
	})
	
	// 返回所有场景数据
	ipcMain.handle('mobile-scene', () => {
		return {
			scenes: allMobleScene,
			index: currentSceneIndex
		}
	})

	// 切换到index场景
	ipcMain.on('select-mobile-scene', (event, index) => {
		// currentScene = allMobleScene[index]
		currentSceneIndex = index
		// 重新设置大小
		mobileFrame.setSize(allMobleScene[index].width, allMobleScene[index].height)
		if (mobileFrame != null && !mobileFrame.isDestroyed()) {
			mobileFrame.webContents.send('on-current-mobile-scene-changed', {
				scene: allMobleScene[index],
				index: index
			})
		}
	})
	
	// 返回场景是否在编辑状态
	ipcMain.handle('mobile-scene-is-edit', () => {
		return mobileEdit
	})
	
	// 切换场景状态
	ipcMain.on('mobile-scene-edit-change-to', (event, edit) => {
		noticeEditChanged(edit)
	})

	// 创建新场景
	ipcMain.handle('create-mobile-scene', (event) => {
		noticeEditChanged(true)
		let cs = {
			user_code: user_code,
			title: '新场景',
			desc: '场景说明',
			allComponents: []
		}
		const primaryDisplay = screen.getPrimaryDisplay()
		const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize
		let mh = parseInt(screenHeight * 0.9)
		// let mw = parseInt(mh * 1179 / 2556)
		let mw = parseInt(mh * 9 / 16)
		cs.width = mw
		cs.height = mh
		if (mobileFrame == null || mobileFrame.isDestroyed()) {
			
			// const primaryDisplay = screen.getPrimaryDisplay()
			// const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize
			// let mh = parseInt(screenHeight * 0.9)
			// let mw = parseInt(mh * 1179 / 2556)
			// cs.width = mw
			// cs.height = mh + 100
			cs.id = db.insertMobleScene(cs)
			allMobleScene.push(cs)
			// currentScene = cs
			currentSceneIndex = allMobleScene.length - 1
			createMobileFrame()
		} else {
			// const [width, height] = mobileFrame.getSize()
			// cs.width = width
			// cs.height = height
			cs.id = db.insertMobleScene(cs)
			allMobleScene.push(cs)
			// currentScene = cs
			currentSceneIndex = allMobleScene.length - 1
		}
		return allMobleScene[currentSceneIndex]
	})
	
	// 获取当前场景数据
	ipcMain.handle('current-mobile-scene-data', (event) => {
		return {
			scene: allMobleScene[currentSceneIndex],
			index: currentSceneIndex
		}
	})
	
	// 打开添加组件窗口
	ipcMain.on('show-add-components-win', (event) => {
		
		const topWindow = BrowserWindow.getFocusedWindow()
		
		if (selectAddComponentsWin == null || selectAddComponentsWin.isDestroyed()) {
			const primaryDisplay = screen.getPrimaryDisplay()
			const { height: screenHeight } = primaryDisplay.workAreaSize
			selectAddComponentsWin = new BrowserWindow({
				width: 290,
				height: parseInt(screenHeight / 2),
				webPreferences: {
					preload: path.join(__dirname, 'preload.js')
				}
			})
			wins.push(selectAddComponentsWin)
		}
		selectAddComponentsWin.loadURL('http://localhost:8080/#/pages/select-add-components-page/select-add-components-page')
		
		selectAddComponentsWin.show()
		selectAddComponentsWin.focus()
		
		// 禁用其他窗口
		BrowserWindow.getAllWindows().forEach(win => {
			if (win !== selectAddComponentsWin) {
				win.setEnabled(false)  // 禁用窗口交互
			}
		})
		
		// 当焦点窗口关闭时重新启用其他窗口
		selectAddComponentsWin.on('closed', () => {
			BrowserWindow.getAllWindows().forEach(win => {
				win.setEnabled(true)
				win.moveTop()
			})
			topWindow.moveTop()
		})
	})
	
	// 当前场景中添加组件
	ipcMain.on('add-component', (event, cpt_name, style) => {
		let bInfo = createComponentBaseInfo(cpt_name, style)
		const scene = allMobleScene[currentSceneIndex]
		scene.allComponents.push(bInfo)
		db.insertComponents(scene.id, scene.allComponents)
		for (let win of wins) {
			if (win != null && !win.isDestroyed()) {
				//  在用
				win.webContents.send('notice-scene-changed', scene, currentSceneIndex, -1, 'select-add-components-page')
			}
		}
		if (selectAddComponentsWin != null && !selectAddComponentsWin.isDestroyed()) {
			selectAddComponentsWin.close()
		}
	})
	
	// 接受该组件新值，并传递给html
	ipcMain.on('component-data-changed-to-main', (event, cpt, to, del_temp_id) => {
		if (!mobileEdit) return
		const noti_name = 'on-component-data-changed-to-html'
		if (to == 'mobileFrame' && mobileFrame != null && !mobileFrame.isDestroyed()) {
			mobileFrame.webContents.send(noti_name, cpt, del_temp_id)
		}
		if (to == 'mainWin' && mainWin != null && !mainWin.isDestroyed()) {
			mainWin.webContents.send(noti_name, cpt, del_temp_id)
		}
	})
	
	// 让index选中当前场景编辑
	ipcMain.on('go-to-select-current-scene', (event) => {
		mainWin.webContents.send('go-to-select-current-scene-html', currentSceneIndex)
	})
	
	// 添加主播窗口打开（也可以是编辑）
	ipcMain.on('add-user-alert', (event) => {
		editUserIndex = -1
		createAddUserAlert()
		addUserAlert.show()
	})
	
	// 编辑主播弹窗
	ipcMain.on('edit-user-alert', (event, index) => {
		editUserIndex = index
		createAddUserAlert()
		addUserAlert.show()
	})
	
	// 获取正在编辑的用户
	ipcMain.handle('get-edit-user-info', () => {
		if (editUserIndex == -1) {
			return null
		}
		return userList[editUserIndex]
	})

	ipcMain.handle('select-image', async () => {
	  const result = await dialog.showOpenDialog({
	    title: '选择图片',
	    properties: ['openFile'],
	    filters: [{ name: '图片文件', extensions: ['jpg', 'jpeg', 'png', 'gif'] }],
	  });
	
	  if (!result.canceled && result.filePaths.length > 0) {
	    const sourcePath = result.filePaths[0]; // 原始图片路径
	    const imagesDir = path.join(__dirname, 'images'); // 目标目录（./images/）
	    
	    // 确保 images 目录存在
	    try {
	      await fs.access(imagesDir);
	    } catch (err) {
	      await fs.mkdir(imagesDir, { recursive: true });
	    }
	
	    // 生成目标路径（如 ./images/photo123.jpg）
	    const fileName = path.basename(sourcePath);
	    const destPath = path.join(imagesDir, fileName);
	
	    // 复制文件到 ./images/
	    await fs.copyFile(sourcePath, destPath);
	
	    // 读取复制的图片并转为 DataURL
	    const image = nativeImage.createFromPath(destPath);
	    return {
			base_64: image.toDataURL(),
			path: destPath
		}
	  }
	  return null; // 用户取消选择
	})
	
	ipcMain.on('select-gif-alert', (event, userInfo, from) => {
		createSelectGifAlert(userInfo)
		selectGifAlert.show()
		selectGifAlert.loadURL('http://localhost:8080/#/pages/select-gif-alert/select-gif-alert?from=' + from)
	}),
	
	// 打开小红书直播间
	ipcMain.on('select-gift', (event, gift, to) => {
		if (to == 'add-user-alert' && addUserAlert != null && !addUserAlert.isDestroyed()) {
			addUserAlert.webContents.send('on-select-gift-to-html', gift)
		}
		selectGifAlert.close()
	})
	
	// 添加主播（或者是编辑）完成
	ipcMain.on('finish-user', (event, userInfo, uType, from) => {
		if (uType == 'add-user') {
			userInfo.user_code = user_code
			userInfo.show = 0
			userInfo.id = db.insertUser(userInfo)
			userInfo.total_gift_coins = 0
			userInfo.now_gift_coins = 0
			userList.unshift(userInfo)
		}
		if (uType == 'edit-user') {
			db.saveUser(userInfo)
			Object.assign(userList[editUserIndex], userInfo)
			
			// 变更组件绑定
			// 通知关系数据有变化
			for (let win of wins) {
				if (win != null && !win.isDestroyed()) {
					//  在用
					win.webContents.send('notice-user-cpt-temp-changed', from)
				}
			}
		}
		for (let win of wins) {
			if (win != null && !win.isDestroyed()) {
				// 在用
				win.webContents.send('notice-user-list-changed', userList, from)
			}
		}
		if (addUserAlert && !addUserAlert.isDestroyed()) {
			addUserAlert.close()
		}
	})

	// 修改主播数据
	ipcMain.on('change-user-info', (event, userInfo, index, cloudDb, from) => {
		if (cloudDb) {
			db.saveUser(userInfo)
		}
		Object.assign(userList[index], userInfo)
		for (let win of wins) {
			if (win != null && !win.isDestroyed()) {
				//  在用
				win.webContents.send('notice-user-list-changed', userList, from)
				// 变更组件绑定
				// 通知关系数据有变化
				win.webContents.send('notice-user-cpt-temp-changed', from)
			}
		}
	})

	// 获取主播列表
	ipcMain.handle('user-list', (event, table_user_temp, cpt_id) => {
		if (!table_user_temp) {
			return userList
		}
		for (let user of userList) {
			const user_cpt_temp = db.selectTableTemp(table_user_temp, user.id, cpt_id, user_code)
			if (user_cpt_temp && user_cpt_temp != null && type(user_cpt_temp) != 'undefined') {
				user.user_cpt_temp = user_cpt_temp
			} else {
				user.user_cpt_temp = null
			}
		}
		return userList
	})

	// 删除主播
	ipcMain.on('del-user', (event, userInfo) => {
		db.delUser(userInfo.id)
		let delU = null
		for (let user of userList) {
			if (user.id == userInfo.id) {
				delU = user
				break
			}
		}
		const index = userList.indexOf(delU);
		if (index > -1) {
			userList.splice(index, 1)
		}
		for (let win of wins) {
			if (win != null && !win.isDestroyed()) {
				//  在用
				win.webContents.send('notice-user-list-changed', userList, 'setting')
				// 变更组件绑定
				// 通知关系数据有变化
				win.webContents.send('notice-user-cpt-temp-changed', 'setting')
			}
		}
	})

	// 获取index场景数据 在用
	ipcMain.handle('get-scene-with-index', (event, index) => {
		return allMobleScene[index]
	})
	
	// 变更index场景数据 在用
	ipcMain.on('scene-changed', (event, scene, index, cpt_index, cloudDb, from) => {
		// 入库
		if (cloudDb) {
			db.saveMobleScene(scene)
			db.insertComponents(scene.id, scene.allComponents)
		}
		allMobleScene[index] = scene
		for (let win of wins) {
			if (win != null && !win.isDestroyed()) {
				//  在用
				win.webContents.send('notice-scene-changed', scene, index, cpt_index, from)
			}
		}
	})
	
	// 更新主播与组件关系表
	ipcMain.on('update-user-cpt-temp', (event, userCptTemp, from) => {
		userCptTemp.user_code = user_code
		const user_cpt_temp = db.selectTableTemp(userCptTemp.table_name, userCptTemp.u_id, userCptTemp.cpt_id, user_code)
		if (user_cpt_temp) {
			db.updateTableTemp(userCptTemp)
		} else {
			db.insertTableTemp(userCptTemp)
		}
		// 通知关系数据有变化
		for (let win of wins) {
			if (win != null && !win.isDestroyed()) {
				//  在用
				win.webContents.send('notice-user-cpt-temp-changed', from)
			}
		}
	})
	
	// 隐藏手机
	ipcMain.on('hidden-mobile', () => {
		if (mobileFrame != null && !mobileFrame.isDestroyed()) {
			const primaryDisplay = screen.getPrimaryDisplay()
			const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize
			mobileFrame.setPosition(screenWidth, screenHeight)
		}
	}),
	
	// 获取模拟场景是否模拟
	ipcMain.handle('mobile-frame-mopni', async () => {
		return mobileFrameMoni
	})
	
	// 设置模拟场景是否模拟
	ipcMain.on('mobile-frame-mopni-to', (event, moni) => {
		mobileFrameMoni = moni
		if (mobileFrame != null && !mobileFrame.isDestroyed()) {
			//  在用
			mobileFrame.webContents.send('on-mobile-frame-mopni-changed', mobileFrameMoni)
		}
	})
	// 获取模拟器是否最小化
	ipcMain.handle('mobile-frame-is-min', async () => {
		return mobileFrameIsMin()
	})
	
	// 隐藏模拟器
	ipcMain.on('mobile-frame-set-min-or-max', (event, min) => {
		if (mobileFrame != null && !mobileFrame.isDestroyed()) {
			if (min) {
				const primaryDisplay = screen.getPrimaryDisplay()
				const { width: screenWidth, height: screenHeight } = primaryDisplay.workAreaSize
				mobileFrame.setPosition(screenWidth, screenHeight)
			} else {
				const primaryDisplay = screen.getPrimaryDisplay()
				const { height: screenHeight } = primaryDisplay.workAreaSize
				let h = parseInt(screenHeight * 0.9)
				mobileFrame.setPosition(40, screenHeight - h - 48)
				mobileFrame.moveTop()
			}
		}
	})
	
	// 获取总信息台数据
	ipcMain.handle('get-console-story', (event, lastId, type) => {
		return db.getConsole_story(user_code, type)
	})
	// 获取总榜单
	ipcMain.handle('get-all-fans-sort', (event) => {
		return db.getAllFans(user_code)
	})
	// 本场直播榜单
	ipcMain.handle('get-now-fans-sort', (event) => {
		// setting
		const room_id = db.selectSystem_setting('room_id').value
		if (room_id == 0) {
			return []
		}
		// 查询本场榜单
		return db.getNowFans(user_code, room_id)
	})

	// 获取系统设置
	ipcMain.handle('get-system-setting', (event, setting) => {
		return db.selectSystem_setting(setting)
	})
	// 更新系统设置
	ipcMain.on('system-setting-change-to', (event, setting, value, from) => {
		db.updateSystem_setting(setting, value)
		const settingVal = db.selectSystem_setting(setting)
		for (let win of wins) {
			if (win != null && !win.isDestroyed()) {
				//  在用
				win.webContents.send('on-system-setting-changed', settingVal, from)
			}
		}
	})
	
	// 弹出绑定菜单
	ipcMain.on('show-bind-to', (event, fans_id, user_id, x, y) => {
		let h = 0
		const scaleFactor = screen.getPrimaryDisplay().scaleFactor
		for (let user of userList) {
			if (user.id != user_id && user.show == 1) {
				h += 50 * scaleFactor
			}
		}
		if (h > 0) {
			showBindTo(fans_id, user_id, x, y, h)
		}
	})
	
	// 获取可以绑定的主播菜单
	ipcMain.handle('get-bind-to-list', (event, type) => {
		let bindUid
		if (type == 1) {
			bindUid = getBindToCurrentUid()
		}
		if (type == 2) {
			bindUid = getCurrentRev_user_id()
		}
		let ul = []
		if (bindUid && bindUid != null) {
			for (let user of userList) {
				if (user.id != bindUid && user.show == 1) {
					ul.push(user)
				}
			}
		}
		return ul
	})
	
	// 重新给粉丝绑定绑定关系
	ipcMain.on('change-bind-to', (event, user_id, type) => {
		if (type == 1) {
			// 将粉丝重新绑定给主播
			const fansId = getBindToCurrentFansUid()
			hideBindTo()
			// 更新粉丝的绑定数据
			db.updateFansBind({
				bind_uid: user_id,
				user_id: fansId,
				user_code: user_code
			})
			// 排行榜发生变化
			if (mainWin != null && !mainWin.isDestroyed()) {
				mainWin.webContents.send('on-fans-sort-changed')
				mainWin.webContents.send('on-now-fans-sort-changed')
			}
		}
		
		if (type == 1) {
			
			// 重新绑定礼物
			const giftStoryId = getCurrentGift_id()
			const rev_user_id = getCurrentRev_user_id()
			hideGiftRebindTo()
			const user_temp_mappings = db.selectUserTempMapping(giftStoryId)
			// 将之前的组件coins票数减掉
			for (let utMp of user_temp_mappings) {
				db.cutUserTempCoins(utMp)
			}
			// 清除组件加票记录
			db.delUser_temp_mapping(giftStoryId)
			// 更新本历史数据的接受者
			db.updateGiftStoryRever(giftStoryId, user_id)
			
			// 给当前场景组件加票数
			// TODO
		}
		
	})
	
	
	// 保存图片
	ipcMain.on('save-gift', async (event, url, fileName) => { // 添加 async
	  try {
	    // 下载图片
	    const response = await fetch(url);
	    const blob = await response.blob();
	    const buffer = Buffer.from(await blob.arrayBuffer());
	    const dDrivePath = path.join('D:', fileName);
	
	    // 保存到 D 盘
	    fs.writeFile(dDrivePath, buffer, (err) => {
	      if (err) {
	        console.error('保存失败:', err);
	        event.reply('save-gift-reply', { success: false, error: err.message });
	      } else {
	        console.log('图片已保存到:', dDrivePath);
	        event.reply('save-gift-reply', { success: true, path: dDrivePath });
	      }
	    });
	  } catch (error) {
	    console.error('下载或保存失败:', error);
	    event.reply('save-gift-reply', { success: false, error: error.message });
	  }
	});
	
	// 获取本场礼物记录
	ipcMain.handle('get-gifts-story', (event) => {
		const room_id = db.selectSystem_setting('room_id').value
		console.log(room_id)
		if (room_id == 0) {
			return []
		}
		const giftsStory = db.getGifts_story(room_id, user_code)
		console.log(giftsStory)
		return giftsStory
	})
	
	// 弹出绑定菜单
	ipcMain.on('show-gift-resend-to', (event, gift_id, rev_user_id, x, y) => {
		let h = 0
		const scaleFactor = screen.getPrimaryDisplay().scaleFactor
		for (let user of userList) {
			if (user.id != rev_user_id && user.show == 1) {
				h += 50 * scaleFactor
			}
		}
		if (h > 0) {
			showGinftReBindTo(gift_id, rev_user_id, x, y, h)
		}
	})
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

